﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CSP.Common.Web;
using CSP.Common.Tools;
using CSP.Model.CSP;
using System.Collections.ObjectModel;
using CSP.Bll;
using CSP.Bll.IObjectBlls;
using Newtonsoft.Json;
using CSP.Web.UserControls;
using CSP.Web.Master;

namespace CSP.Web.MyHome.Address
{
    public partial class Add : CSPMyHome
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            //((HomeMaster)Master).SelectedNavigationLink = MyHomeLeftNavigationLink.Address;
            if (!IsPostBack)
            {
                if (Request["parentid"] != null)
                {
                    int parentId = Convert.ToInt32(Request.QueryString["parentid"]);
                    string serviceTypeJson = GetServiceAreaJsonByParentId(parentId);
                    Response.ClearContent();
                    Response.Write(serviceTypeJson);
                    Response.ContentType = "text/plain";
                    Response.End();
                }
                else if (Request["parentsubid"] != null)
                {
                    int parentSubId = Convert.ToInt32(Request.QueryString["parentsubid"]);
                    string serviceTypeJson = GetServiceAreaJsonByParentId(parentSubId);
                    Response.ClearContent();
                    Response.Write(serviceTypeJson);
                    Response.ContentType = "text/plain";
                    Response.End();
                }
                else
                {
                    BindProvinceUI();
                }
            }
        }


        protected void BtnSubmit_Click(object sender, EventArgs e)
        {
            CreateAddress();
        }

        /// <summary>
        /// 绑定省市UI
        /// </summary>
        private void BindProvinceUI()
        {
            CSPBllFactory factory = CSPBllFactory.GetInstance();
            ICollection<ServiceArea> serviceAreas = new Collection<ServiceArea>();
            using (IServiceAreaBll serviceAreaBll = factory.GetServiceAreaBll())
            {
                serviceAreas = serviceAreaBll.FindByParentId(0);
            }
            this.S_Province.DataSource = serviceAreas.OrderBy(s => s.Orderid);
            this.S_Province.DataTextField = "name";
            this.S_Province.DataValueField = "id";
            this.S_Province.DataBind();
            this.S_Province.Items.Insert(0, new ListItem("请选择", ""));
        }

        private void CreateAddress()
        {
            CSP.Model.CSP.Address address = GetAddAddress();
            CSPBllFactory factory = CSPBllFactory.GetInstance();
            using (IAddressBll addressBll = factory.GetAddressBll())
            {
                try
                {
                    addressBll.Add(address);

                }
                catch (Exception ex)
                {
                    LoggerProvider.Error(ex);
                    this.FailRedirect("提交未失败", "/MyHome/Address/List.aspx");
                }
            }

            if (Request["urlback"] != null)
            {
                Response.Redirect(Request["urlback"].ToString());
            }

            this.SuccessfullRedirect("已经提交成功", "/MyHome/Address/List.aspx");
        }


        private string GetServiceAreaJsonByParentId(int parentId)
        {
            List<ServiceArea> serviceAreas = this.GetServiceAreaByParentId(parentId);
            List<ServiceAreaEntity> serviceAreasEntity = (from area in serviceAreas
                                                          select new ServiceAreaEntity
                                                          {
                                                              Id = area.Id,
                                                              Name = area.Name,
                                                              ParentId = area.Parentid
                                                          }).ToList();

            return JsonConvert.SerializeObject(serviceAreasEntity);
        }

        /// <summary>
        /// 从Bll层根据ParentId获取ServiceAreas
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private List<ServiceArea> GetServiceAreaByParentId(int parentId)
        {
            CSPBllFactory factory = CSPBllFactory.GetInstance();
            List<ServiceArea> result = new List<ServiceArea>();
            ICollection<ServiceArea> serviceAreas = null;
            using (IServiceAreaBll serviceAreaBll = factory.GetServiceAreaBll())
            {
                serviceAreas = serviceAreaBll.FindByParentId(parentId);
            }
            if (serviceAreas != null)
            {
                result = serviceAreas.ToList();
            }
            return result;
        }

        /// <summary>
        /// 获取Add所需的Authentication
        /// </summary>
        /// <returns></returns>
        private CSP.Model.CSP.Address GetAddAddress()
        {
            CSP.Model.CSP.Address address = new Model.CSP.Address();

            address.UserName = UserProvider.UserName;
            address.Name = Txt_Name.Value;
            address.Introduction = Txt_Introduction.Text;
            address.Province = Convert.ToInt32(Txt_Province.Value);
            address.City = Convert.ToInt32(Txt_City.Value);
            address.County = Convert.ToInt32(Txt_County.Value);
            address.Street = Txt_Street.Value;
            address.CN_Province = Txt_CN_Province.Value;
            address.CN_City = Txt_CN_City.Value;
            address.CN_County = Txt_CN_County.Value;
            address.Mobile = Txt_Mobile.Value;
            address.Telephone = Txt_Phone.Value;
            address.Email = Txt_Email.Value;
            address.LastModified = BitConverter.GetBytes(CommonTool.ConvertToTimeSpan(DateTime.Now));
            address.Maps = GetAddMap();
            
            return address;
        }

        /// <summary>
        /// 获取要添加的Map
        /// </summary>
        /// <returns></returns>
        private ICollection<Map> GetAddMap()
        {
            ICollection<Map> result = new Collection<Map>();
            Map map = new Map
            {
                CenterPointX = Txt_CenterPointX.Value,
                CenterPointY = Txt_CenterPointY.Value,
                MarkerPointX = Txt_MarkerPointX.Value,
                MarkerPointY = Txt_MarkerPointY.Value,
                Zoom = Convert.ToInt32(Txt_Zoom.Value),
                //LastModified = BitConverter.GetBytes(CommonTool.ConvertToTimeSpan(DateTime.Now)),
            };

            result.Add(map);
            return result;
        }

        private class ServiceAreaEntity
        {
            public int Id { get; set; }

            public string Name { get; set; }

            public int ParentId { get; set; }
        }
    }
}